import axios from 'axios'
import { useUserStore } from '@/stores/user'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token.startsWith('Bearer ') 
        ? userStore.token 
        : `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      // 服务器返回错误状态码
      console.error('Response Error:', error.response.data)
    } else if (error.request) {
      // 请求发出但没有收到响应
      console.error('Request Error:', error.message)
    } else {
      // 请求配置出错
      console.error('Error:', error.message)
    }
    return Promise.reject(error)
  }
)

export default request 